package org.example.protocol;

import io.vertx.core.buffer.Buffer;
import org.example.enums.ProtocolMessageSerializerEnum;
import org.example.serializer.Serializer;
import org.example.serializer.SerializerFactory;
import org.example.serializer.SerializerFactorySpi;

import java.io.IOException;

import static io.netty.buffer.Unpooled.buffer;

/**
 * @description TODO
 * @author sats@jz
 * @date 2025年01月06日 11:00
 */
public class ProtocolMessageEncoder {



    public static Buffer encoder(ProtocolMessage<?> protocolMessage) throws IOException{
        if(protocolMessage == null || protocolMessage.getHeader() == null){
            return Buffer.buffer();
        }

        ProtocolMessage.Header header = protocolMessage.getHeader();

        // 依次像缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic())
                .appendByte(header.getVersion())
                .appendByte(header.getSerializer())
                .appendByte(header.getMessageType())
                .appendByte(header.getStatus())
                .appendLong(header.getRequestId());
        // 获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerEnum == null) {
            throw  new RuntimeException("序列化协议不存在");
        }

        Serializer serializer = SerializerFactorySpi.getInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }



}
